package com.lik888.filter;

import cn.hutool.jwt.JWTUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.lik888.entity.QxUser;
import com.lik888.entity.UserLogin;
import com.lik888.mapper.QxUserMapper;
import com.lik888.utils.JwtTool;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;
import java.security.Security;
import java.util.ArrayList;
import java.util.List;

@RequiredArgsConstructor
@Component

public class JWTAuthenticationfilter  extends OncePerRequestFilter {
    private final StringRedisTemplate stringRedisTemplate;
    private final JwtTool jwtTool;
    private final ObjectMapper objectMapper;
    private final RedisTemplate redisTemplate;
    private final QxUserMapper qxUserMapper;


    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String requestURI = request.getRequestURI();
        //判断
        if(requestURI.equals("/user/login")){
            filterChain.doFilter(request, response);
            return;
        }

        if(requestURI.equals("/auth/reader")){
            filterChain.doFilter(request, response);
            return;
        }

        if(requestURI.equals("/auth/callback")){
            filterChain.doFilter(request, response);
            return;
        }

        String authorization = request.getHeader("Authorization");
        if(!StringUtils.hasText(authorization)){
            throw new RuntimeException("Authorizatio n header is empty");
        }
        Long l = jwtTool.parseToken(authorization);
        System.out.println(l);

        String token = stringRedisTemplate.opsForValue().get("securitydemo:user:"+l);
        if(!StringUtils.hasText(token)){
            throw new RuntimeException("token is empty");
        }


        //TODO 从数据库中获取权限
        List<QxUser> qxUsers = qxUserMapper.selectList(new QueryWrapper<QxUser>().eq("userid", l));
        //判断是否有权限
        if(qxUsers.isEmpty()){
            throw new RuntimeException("user has no permission");
        }
        List<SimpleGrantedAuthority> authorities = new ArrayList<>();
        qxUsers.forEach(qxUser -> {
            authorities.add(new SimpleGrantedAuthority(qxUser.getPermission()));
        });
        System.out.println(authorities);

        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(token,null, authorities);
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        filterChain.doFilter(request, response);
    }
}
